import ParserBase from "../../parser/ParserBase";
import BaseElement from "../../ui/core/BaseElement";
import TextEditer from "./TextEditer";

export default class FileEditParser extends ParserBase{
    page=new BaseElement();
    filePath?:string
    async getFileData(path:string){
        return await this.exec(`cat ${path}`);
    }
    async onConnected(){
        if(this.filePath){
            let rel=await this.getFileData(this.filePath);
            if(rel.exitCode>0){
                alert("发生错误，代码："+rel.exitCode)
            }
            console.error(rel.data);
            let p= <TextEditer>this.page;
            p.setText(rel.data);
            p.addEventListener("save",async e=>{
                if(this.filePath){
                    let rel = await this.setFileText(this.filePath,p.getText());
                    if(rel.exitCode==0){
                        alert("保存成功！")
                    }else{
                        alert("保存失败！"+rel.exitCode);
                    }
                }else{
                    alert("新建文件的业务逻辑")
                }
                
            })
        }
    }
    setPage(p:BaseElement){
        this.page=p;
    }
    setPath(path:string){
        this.filePath=path
    }
    async setFileText(path:string,text:string){
        return await this.exec(`echo -e "${text}" > ${path}`);
    }
}